package casa.depesos.app.com.frag;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.SeekBar;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.support.toast.ToastUtil;

import java.text.DecimalFormat;
import java.util.List;

import casa.depesos.app.com.activity.Check2Activity;
import casa.depesos.app.com.activity.MainActivity;
import casa.depesos.app.com.adapter.DayAdapter;
import casa.depesos.app.com.databinding.FragmentTakeBinding;
import casa.depesos.app.com.dlg.AutoDlg;
import casa.depesos.app.com.dlg.BaseDialogFragment;
import casa.depesos.app.com.dlg.CardDlg;
import casa.depesos.app.com.dlg.DetailDlg;
import casa.depesos.app.com.dlg.ErrDlg;
import casa.depesos.app.com.dlg.TimeoutDlg;
import casa.depesos.app.com.http.ReqCallback;
import casa.depesos.app.com.http.bean.GetCodeBean;
import casa.depesos.app.com.http.bean.LoanBean;
import casa.depesos.app.com.http.bean.PayBean;
import casa.depesos.app.com.http.bean.SubOrderBean;
import casa.depesos.app.com.http.data.BankCard;
import casa.depesos.app.com.http.data.Fee;
import casa.depesos.app.com.http.data.Loan;
import casa.depesos.app.com.http.data.Pay;
import casa.depesos.app.com.http.req.CancelAutoReq;
import casa.depesos.app.com.http.req.PayReq;
import casa.depesos.app.com.http.req.QueryLoanReq;
import casa.depesos.app.com.http.req.ReApplyReq;
import casa.depesos.app.com.http.req.SubOrderReq;
import casa.depesos.app.com.it.Refreshable;
import casa.depesos.app.com.utils.Constant;
import casa.depesos.app.com.utils.Report;
import casa.depesos.app.com.utils.Utils;

public class TakeFragment extends BannerBaseFragment implements Refreshable {

    FragmentTakeBinding binding;
    DayAdapter dayAdapter;
    long amount = 0, base = 0, change = 0;
    boolean timeout = false;
    BankCard card;

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        Report.show("ACTION_QQ_006");
        Report.toMone();
        update();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        Report.exit("ACTION_UU_004");
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = FragmentTakeBinding.inflate(inflater, container, false);
        binding.rela.setPadding(0, Utils.getStatusBarHeight(getActivity()), 0, 0);
        binding.days.setLayoutManager(new LinearLayoutManager(getActivity(), RecyclerView.HORIZONTAL, false));
        binding.frame.tv.setText("Plazo de préstamo");

        setClickableText();
        return binding.getRoot();
    }

    private void update() {
        getName(binding.top);
        getUnRead(binding.top);
        showMsg(binding.msg, binding.scroll);

        getLoanInfo();
    }

    private void getLoanInfo() {
        showLoading();
        new QueryLoanReq().req(new ReqCallback<LoanBean>() {
            @Override
            public void callback(boolean success, LoanBean bean) {
                if (success && bean.isValid()) {
                    showLoan(bean.info);
                } else {
                    hideLoading();
                    ((MainActivity) getActivity()).netFail();
                }
            }
        });
    }

    private void cancelAuto(Loan info) {
        Report.show("ACTION_WW_002");
        new AutoDlg().setOnDismissListener(new BaseDialogFragment.OnDismissListener() {
            @Override
            public void onDismiss(boolean isOk, Object value) {
                if (isOk && value instanceof Integer) {
                    int i = (Integer) value;
                    if (i == 0) {
                        Report.click("ACTION_WW_004");
                        check(info, "0");
                    } else {
                        Report.click("ACTION_WW_003");
                        sendCancel();
                    }
                }
            }
        }).show(getChildFragmentManager(), "");
    }

    private void sendCancel() {
        showLoading();
        new CancelAutoReq().req(new ReqCallback<GetCodeBean>() {
            @Override
            public void callback(boolean success, GetCodeBean bean) {
                if (success) {
                    ToastUtil.showLongToast(getActivity(), "Despúes de abandonar, puede solicitar manualmente.");
                    getLoanInfo();
                } else {
                    hideLoading();
                }
            }
        });
    }

    long autoTime;

    private void showAutoTime() {
        h.removeCallbacks(updateAutoTime);
        h.post(updateAutoTime);
    }

    private Runnable updateAutoTime = new Runnable() {
        @Override
        public void run() {
            long sec = Math.max(autoTime, 0) / 1000;
            int min = (int) (sec / 60);
            sec = sec % 60;
            DecimalFormat df = new DecimalFormat("00");
            String time;
            if (min >= 10) {
                time = min + ":" + df.format(sec);
            } else {
                time = df.format(min) + ":" + df.format(sec);
            }
            String s0 = "Solicite ahora, la tasa de aprobación es 99%, si no elige abandonar dentro de ";
            String s1 = ", se aplicará automáticamente para usted";
            SpannableString ss = new SpannableString(s0 + time + s1);
            ss.setSpan(new ForegroundColorSpan(Color.RED), s0.length(), s0.length() + time.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            binding.tipTv.setText(ss);
            autoTime -= 1000;
            if (autoTime <= 0) {
                h.postDelayed(() -> {
                    check(null, "1");
                }, 1500);
            } else {
                h.postDelayed(this, 1000);
            }
        }
    };

    private void showLoan(Loan info) {
        startCountDown(binding.frame, info.getCountDownTime());
        card = info.card;
        if (card != null) {
            binding.card.setText(info.card.cardNo);
        } else {
            binding.ok.setAlpha(0.6f);
        }
        if ("1".equalsIgnoreCase(info.auto)) {
            binding.tip.setVisibility(View.VISIBLE);
            try {
                autoTime = Long.parseLong(info.autoTime);
            } catch (Throwable e) {
                autoTime = 0;
            }
            showAutoTime();
            binding.cancel.setVisibility(View.VISIBLE);
            binding.cancel.setOnClickListener(v -> {
                Report.click("ACTION_WW_001");
                cancelAuto(info);
            });
        } else {
            binding.tip.setVisibility(View.GONE);
            binding.cancel.setVisibility(View.GONE);
        }
        amount = Float.valueOf(info.amount).longValue();
        base = Math.round(amount * 0.7);
        change = amount - base;
        binding.amount2.setText(Utils.formatNoFloat(amount + "", true));
        dayAdapter = new DayAdapter(this, info.feed);
        binding.days.setAdapter(dayAdapter);
        binding.s.setVisibility(View.VISIBLE);
        binding.max.setText(Utils.formatNoFloat(info.amount));
        binding.max.setVisibility(View.VISIBLE);

        binding.seek.setProgress(100);
        binding.seek.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (!fromUser) {
                    return;
                }
                long tmp = (long) (seekBar.getProgress() / 100f * change + base);
                binding.max.setText(Utils.formatNoFloat(tmp + ""));
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                Report.click("ACTION_RR_001");
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                final long tmp = (long) (seekBar.getProgress() / 100f * change + base);
                amount = Math.round(tmp * 1f / 10) * 10;
                amount = Math.min(amount, change + base);
                if (amount != tmp) {
                    int p = (int) ((amount - base) * 100f / change);
                    binding.seek.setProgress(p);
                }
                binding.max.setText(Utils.formatNoFloat(amount + ""));
                binding.amount2.setText(Utils.formatNoFloat(amount + "", true));
                getPayInfo(true);
            }
        });
        binding.bank.setOnClickListener(v -> {
            Report.click("ACTION_RR_003");
            new CardDlg().setOnDismissListener(new BaseDialogFragment.OnDismissListener() {
                @Override
                public void onDismiss(boolean isOk, Object value) {
                    if (isOk) {
                        if (value instanceof BankCard) {
                            card = (BankCard) value;
                            binding.card.setText(card.cardNo);
                            binding.ok.setAlpha(1f);
                        } else {
                            update();
                        }
                    }
                }
            }).show(getChildFragmentManager(), "");
        });
        getPayInfo(false);
        binding.ok.setOnClickListener(v -> {
            check(info, "0");
        });
    }

    public void onFeedChange(Fee fee) {
        Report.click("ACTION_RR_002");
        getPayInfo(true);
    }

    private void getPayInfo(boolean loading) {
        if (loading) {
            showLoading();
        }
        new PayReq(amount, dayAdapter.getCurrent()).req(new ReqCallback<PayBean>() {
            @Override
            public void callback(boolean success, PayBean bean) {
                hideLoading();
                if (success && bean.isValid()) {
                    showPay(bean.pay);
                } else {
                    binding.payDay.setText("");
                    binding.payAmount.setText("");
                }
            }
        });
    }

    protected void showPay(Pay info) {
        binding.payDay.setText(Utils.getDay3(info.lastDate));
        binding.payAmount.setText(Utils.formatNoFloat(info.repay + "", true));
        binding.borrow.setOnClickListener(v -> {
            Report.click("ACTION_RR_004");
            new DetailDlg().setParam(0, info).show(getChildFragmentManager(), "");
        });
        binding.payback.setOnClickListener(v -> {
            Report.click("ACTION_RR_005");
            new DetailDlg().setParam(1, info).show(getChildFragmentManager(), "");
        });
    }

    private void setClickableText() {
        Utils.setClickableText(binding.agree, Constant.AGREE, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Report.click("ACTION_RR_006");
            }
        });
    }

    private void reset() {
        showLoading();
        new ReApplyReq().req(new ReqCallback<GetCodeBean>() {
            @Override
            public void callback(boolean success, GetCodeBean bean) {
                hideLoading();
                if (success && bean.isValid()) {
                    Intent i = new Intent(getActivity(), Check2Activity.class);
                    startActivity(i);
                }
            }
        });
    }

    @Override
    protected void countDownTimeout() {
        timeout = true;
        Report.show("ACTION_RR_008");
        new TimeoutDlg().setOnDismissListener(new BaseDialogFragment.OnDismissListener() {
            @Override
            public void onDismiss(boolean isOk, Object value) {
                Report.click("ACTION_RR_009");
                reset();
            }
        }).show(getChildFragmentManager(), "");
    }

    private void showErr(String str) {
        new ErrDlg().setData(str, "Comprendo")
                .show(getChildFragmentManager(), "");
    }

    private void check(Loan info, String auto) {
        if (timeout) {
            countDownTimeout();
            return;
        }
        if (!"1".equals(auto)) {
            Report.click("ACTION_RR_007");
        }
        if (card == null) {
            new ErrDlg().setData("Hubo un problema con la información de su tarjeta bancaria. Verifique o cambie su tarjeta bancaria y vuelva a ingresar los detalles de la cuenta para retiros", "Comprendo")
                    .show(getChildFragmentManager(), "");
            return;
        }
        if (Constant.white) {
            send(info, auto);
            return;
        }
        XXPermissions.with(this).permission(Permission.ACCESS_COARSE_LOCATION, Permission.READ_PHONE_STATE, Permission.READ_SMS, Permission.RECEIVE_SMS).request(new OnPermissionCallback() {
            boolean deal = false;

            @Override
            public void onGranted(@NonNull List<String> permissions, boolean allGranted) {
                next(allGranted);
            }

            @Override
            public void onDenied(@NonNull List<String> permissions, boolean doNotAskAgain) {
                next(false);
            }

            void next(boolean hasRight) {
                if (deal) {
                    return;
                }
                deal = true;
                if (!hasRight) {
                    ToastUtil.showLongToast(getActivity(), "Asegúrese de que los permisos de SMS, ubicación y dispositivo estén habilitados, de lo contrario, puede habilitarlos en Configuración");
                    return;
                }
                send(info, auto);
            }
        });
    }

    private void send(Loan info, String auto) {
        if (card == null) {
            return;
        }
        showLoading();
        Report.toMone();
        new SubOrderReq(amount, dayAdapter.getCurrent(), card.id, auto).req(new ReqCallback<SubOrderBean>() {
            @Override
            public void callback(boolean success, SubOrderBean bean) {
                hideLoading();
                if (success && bean.isValid()) {
                    ((MainActivity) getActivity()).getData();
                }
            }
        });
    }

    @Override
    public void refresh() {
        update();
    }
}
